package it.sd.pwframework.business.service.impl;

import it.sd.pwframework.business.bean.common.RemoteMovieBean;
import it.sd.pwframework.business.service.ImdbService;
import it.sd.pwframework.business.service.SpiderService;
import it.sd.utility.XMLWrapper;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

@Service("imdbService")
public class ImdbServiceImpl implements ImdbService {

    protected Logger log = org.slf4j.LoggerFactory.getLogger(this.getClass());
    
    @Autowired
    private SpiderService spiderService;
    
	public List<RemoteMovieBean> downloadListMovies() throws Exception {
		
		
		HashMap<String, String> params = new HashMap<String, String>();
		params.put("startpage", "1");
		params.put("maxpage", "100");

		XMLWrapper xml = spiderService.executeService("imdb.scifi.list", params);

		LinkedList<RemoteMovieBean> lista = createLista(xml);

		return lista;
	}
	
	private LinkedList<RemoteMovieBean> createLista(XMLWrapper xml) throws Exception {
		LinkedList<RemoteMovieBean> lista = new LinkedList<RemoteMovieBean>();

		NodeList nodeList = xml.extractNodeValue("//movie");
		for (int i = 0; i < nodeList.getLength(); i++) {
			Node node = nodeList.item(i);
			if (node instanceof Element) {
				RemoteMovieBean bean = createElement((Element)node);
				if (bean!=null) lista.add(bean);
			}
		}
		
		return lista;
		
	}
	
	private RemoteMovieBean createElement(Element e) {
		
		RemoteMovieBean movie = null;
		
		try {
			movie = new RemoteMovieBean();
			
			Element identification = XMLWrapper.getFiglio(e, "identification"); 
			String title = XMLWrapper.getFiglioContent(identification, "title");
			String id = XMLWrapper.getFiglioContent(identification, "id");
			String year = XMLWrapper.getFiglioContent(e, "year");
			movie.setId(id);
			movie.setTitle(title);
			movie.setYear(Integer.parseInt(year));
			/*
			<identification>
				<title>Inception</title>
				<id>/title/tt1375666/</id>
			</identification>
			<year>2010</year>
			<voto>8.8</voto>
			*/
			
		} catch (Exception e2) {
			log.error("Error retrieve movie data: " + movie, e2);
			movie = null;
		}
		
		return movie;
	}

	
}
